// 游戏配置
const ICONS = ['🍎', '🍌', '🍒', '🍓', '🍊', '🍇', '🍉', '🍋'];
const DIFFICULTIES = {
  easy: { rows: 6, cols: 6 },
  medium: { rows: 8, cols: 8 },
  hard: { rows: 10, cols: 10 }
};

// 新增：最小方块尺寸
const MIN_TILE_SIZE = 40;

// 游戏状态
let gameBoard = [];
let selectedTiles = [];
let score = 0;
let timer;
let seconds = 0;
let currentDifficulty = 'medium';
let currentLanguage = 'zh';

function setLanguage(lang) {
  currentLanguage = lang;
  updateTranslations();
}

function updateTranslations() {
  document.getElementById('game-title').textContent = translations[currentLanguage].title;
  document.getElementById('score').textContent = `${translations[currentLanguage].score}: ${score}`;
  document.getElementById('timer').textContent = `${translations[currentLanguage].time}: ${seconds}${translations[currentLanguage].seconds}`;
  document.getElementById('new-game').textContent = translations[currentLanguage].newGame;
  document.getElementById('hint').textContent = translations[currentLanguage].hint;
  
  // 更新难度选择器
  const difficultySelector = document.getElementById('difficulty-selector');
  difficultySelector.innerHTML = '';
  Object.keys(DIFFICULTIES).forEach(difficulty => {
    const option = document.createElement('option');
    option.value = difficulty;
    option.textContent = translations[currentLanguage][difficulty];
    difficultySelector.appendChild(option);
  });
  difficultySelector.value = currentDifficulty;
}

function setDifficulty(difficulty) {
  currentDifficulty = difficulty;
  adjustGameSize();
  initializeGame();
}

function adjustGameSize() {
  const gameContainer = document.getElementById('game-container');
  const gameBoard = document.getElementById('game-board');
  const { rows, cols } = DIFFICULTIES[currentDifficulty];

  // 计算可用空间
  const availableWidth = gameContainer.clientWidth;
  const availableHeight = window.innerHeight * 0.6; // 使用窗口高度的60%

  // 计算方块大小
  const tileSize = Math.floor(Math.min(
    (availableWidth - 2) / cols,  // 减去2是为了考虑游戏板的边框
    (availableHeight - 2) / rows,
    60 // 最大尺寸
  ));

  // 设置游戏板样式
  gameBoard.style.gridTemplateColumns = `repeat(${cols}, ${tileSize}px)`;
  gameBoard.style.gridTemplateRows = `repeat(${rows}, ${tileSize}px)`;

  // 更新 CSS 变量
  document.documentElement.style.setProperty('--tile-size', `${tileSize}px`);
  document.documentElement.style.setProperty('--font-size', `${Math.max(tileSize * 0.5, 16)}px`);

  // 更新游戏板的整体大小
  const boardWidth = cols * tileSize + (cols - 1) + 2; // 加上间隙和边框
  const boardHeight = rows * tileSize + (rows - 1) + 2;
  gameBoard.style.width = `${boardWidth}px`;
  gameBoard.style.height = `${boardHeight}px`;
}

function initializeGame() {
  const { rows, cols } = DIFFICULTIES[currentDifficulty];
  gameBoard = [];
  selectedTiles = [];
  const gameBoardElement = document.getElementById('game-board');
  gameBoardElement.innerHTML = '';

  // 创建游戏板
  for (let i = 0; i < rows; i++) {
    const row = [];
    for (let j = 0; j < cols; j++) {
      const tile = document.createElement('div');
      tile.classList.add('tile');
      tile.dataset.row = i;
      tile.dataset.col = j;
      tile.addEventListener('click', onTileClick);
      gameBoardElement.appendChild(tile);
      row.push(ICONS[Math.floor(Math.random() * ICONS.length)]);
    }
    gameBoard.push(row);
  }

  // 确保游戏上有可消除的方块对
  while (!hasPossibleMoves()) {
    shuffleBoard();
  }

  updateBoard();
  score = 0;
  updateScore(0);
  seconds = 0;
  startTimer();
}

function hasPossibleMoves() {
  for (let i = 0; i < gameBoard.length; i++) {
    for (let j = 0; j < gameBoard[i].length; j++) {
      if (gameBoard[i][j] !== '') {
        for (let x = i; x < gameBoard.length; x++) {
          for (let y = (x === i ? j + 1 : 0); y < gameBoard[x].length; y++) {
            if (canConnect({ row: i, col: j }, { row: x, col: y })) {
              return true;
            }
          }
        }
      }
    }
  }
  return false;
}

function shuffleBoard() {
  const allTiles = gameBoard.flat().filter(tile => tile !== '');
  for (let i = 0; i < gameBoard.length; i++) {
    for (let j = 0; j < gameBoard[i].length; j++) {
      if (gameBoard[i][j] !== '') {
        const randomIndex = Math.floor(Math.random() * allTiles.length);
        gameBoard[i][j] = allTiles[randomIndex];
        allTiles.splice(randomIndex, 1);
      }
    }
  }
}

function updateBoard() {
  const tiles = document.querySelectorAll('.tile');
  tiles.forEach((tile) => {
    const row = parseInt(tile.dataset.row);
    const col = parseInt(tile.dataset.col);
    tile.textContent = gameBoard[row][col];
  });
}

function onTileClick(event) {
  const tile = event.target;
  const row = parseInt(tile.dataset.row);
  const col = parseInt(tile.dataset.col);

  if (selectedTiles.length === 0) {
    selectedTiles.push({ row, col });
    tile.classList.add('selected');
  } else if (selectedTiles.length === 1) {
    const firstTile = selectedTiles[0];
    if (firstTile.row === row && firstTile.col === col) {
      selectedTiles = [];
      tile.classList.remove('selected');
    } else {
      selectedTiles.push({ row, col });
      tile.classList.add('selected');
      checkMatch();
    }
  }
}

function checkMatch() {
  const [tile1, tile2] = selectedTiles;
  const path = findPath(tile1, tile2);
  if (path) {
    const targetIcon = gameBoard[tile1.row][tile1.col];
    const tilesToRemove = collectAllMatchingTiles(path, targetIcon);
    
    // 标记要移除的方块
    tilesToRemove.forEach(tile => {
      const tileElement = document.querySelector(`.tile[data-row="${tile.row}"][data-col="${tile.col}"]`);
      tileElement.classList.add('matched');
    });
    
    showConnectionPath(path);
    
    // 使用 Promise 来确保动画完成后再更新游戏板
    new Promise(resolve => {
      setTimeout(() => {
        tilesToRemove.forEach(tile => {
          gameBoard[tile.row][tile.col] = '';
        });
        updateBoard();
        removeConnectionPath();
        resolve();
      }, 500);
    }).then(() => {
      if (isGameOver()) {
        stopTimer();
        showGameOverScreen();
      } else if (!hasPossibleMoves()) {
        // 如果没有可能的移动但游戏还没结束，重新洗牌
        shuffleBoard();
        updateBoard();
      }
    });
    
    updateScore(tilesToRemove.length * 10);
  } else {
    selectedTiles.forEach(tile => {
      const tileElement = document.querySelector(`.tile[data-row="${tile.row}"][data-col="${tile.col}"]`);
      tileElement.classList.add('error');
      setTimeout(() => {
        tileElement.classList.remove('error');
      }, 300);
    });
  }
  
  selectedTiles.forEach((tile) => {
    document.querySelector(`.tile[data-row="${tile.row}"][data-col="${tile.col}"]`).classList.remove('selected');
  });
  selectedTiles = [];
}

function showConnectionPath(path) {
  const pathElement = document.createElement('div');
  pathElement.id = 'connection-path';
  pathElement.style.position = 'absolute';
  pathElement.style.zIndex = '1000';
  document.getElementById('game-board').appendChild(pathElement);

  for (let i = 0; i < path.length - 1; i++) {
    drawLine(path[i], path[i + 1]);
  }
}

function findPath(tile1, tile2) {
  const targetIcon = gameBoard[tile1.row][tile1.col];
  const queue = [[tile1]];
  const visited = new Set();
  const key = (tile) => `${tile.row},${tile.col}`;

  while (queue.length > 0) {
    const path = queue.shift();
    const current = path[path.length - 1];

    if (current.row === tile2.row && current.col === tile2.col) {
      return path;
    }

    const directions = [
      {row: -1, col: 0}, {row: 1, col: 0},
      {row: 0, col: -1}, {row: 0, col: 1}
    ];

    for (const dir of directions) {
      const next = {row: current.row + dir.row, col: current.col + dir.col};
      const nextKey = key(next);

      if (next.row < 0 || next.row >= gameBoard.length || 
          next.col < 0 || next.col >= gameBoard[0].length ||
          visited.has(nextKey)) {
        continue;
      }

      const nextIcon = gameBoard[next.row][next.col];
      if (nextIcon === '' || nextIcon === targetIcon) {
        visited.add(nextKey);
        queue.push([...path, next]);
      }
    }
  }

  return null;
}

function collectAllMatchingTiles(path, targetIcon) {
  const matchingTiles = [];
  for (const tile of path) {
    if (gameBoard[tile.row][tile.col] === targetIcon) {
      matchingTiles.push(tile);
    }
  }
  return matchingTiles;
}

function drawLine(start, end) {
  const line = document.createElement('div');
  line.className = 'connection-line';
  
  const tileSize = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--tile-size'));
  const startX = start.col * tileSize + tileSize / 2;
  const startY = start.row * tileSize + tileSize / 2;
  const endX = end.col * tileSize + tileSize / 2;
  const endY = end.row * tileSize + tileSize / 2;
  
  const length = Math.sqrt(Math.pow(endX - startX, 2) + Math.pow(endY - startY, 2));
  const angle = Math.atan2(endY - startY, endX - startX) * 180 / Math.PI;
  
  line.style.width = `${length}px`;
  line.style.left = `${startX}px`;
  line.style.top = `${startY}px`;
  line.style.transform = `rotate(${angle}deg)`;
  
  document.getElementById('connection-path').appendChild(line);
}

function removeConnectionPath() {
  const pathElement = document.getElementById('connection-path');
  if (pathElement) {
    pathElement.remove();
  }
}

function isGameOver() {
  return !hasPossibleMoves();
}

function startTimer() {
  stopTimer();
  timer = setInterval(() => {
    seconds++;
    document.getElementById('timer').textContent = `${translations[currentLanguage].time}: ${seconds}${translations[currentLanguage].seconds}`;
  }, 1000);
}

function stopTimer() {
  if (timer) {
    clearInterval(timer);
  }
}

function updateScore(points) {
  score += points;
  document.getElementById('score').textContent = `${translations[currentLanguage].score}: ${score}`;
}

function findHint() {
  for (let i = 0; i < gameBoard.length; i++) {
    for (let j = 0; j < gameBoard[i].length; j++) {
      if (gameBoard[i][j] !== '') {
        for (let x = i; x < gameBoard.length; x++) {
          for (let y = (x === i ? j + 1 : 0); y < gameBoard[x].length; y++) {
            if (canConnect({ row: i, col: j }, { row: x, col: y })) {
              return { tile1: { row: i, col: j }, tile2: { row: x, col: y } };
            }
          }
        }
      }
    }
  }
  return null;
}

function showHint() {
  const hint = findHint();
  if (hint) {
    const tile1 = document.querySelector(`.tile[data-row="${hint.tile1.row}"][data-col="${hint.tile1.col}"]`);
    const tile2 = document.querySelector(`.tile[data-row="${hint.tile2.row}"][data-col="${hint.tile2.col}"]`);
    tile1.classList.add('hint');
    tile2.classList.add('hint');
    
    // 显示连接路径
    const path = findPath(hint.tile1, hint.tile2);
    showConnectionPath(path);
    
    setTimeout(() => {
      tile1.classList.remove('hint');
      tile2.classList.remove('hint');
      removeConnectionPath();
    }, 2000);
  }
}

function canConnect(tile1, tile2) {
  if (gameBoard[tile1.row][tile1.col] !== gameBoard[tile2.row][tile2.col]) {
    return false;
  }
  const path = findPath(tile1, tile2);
  return path !== null;
}

function showGameOverScreen() {
  saveHighScore();
  const highScore = localStorage.getItem('highScore');
  
  const gameOverScreen = document.createElement('div');
  gameOverScreen.id = 'game-over-screen';
  gameOverScreen.innerHTML = `
    <h2>${translations[currentLanguage].gameOver}</h2>
    <p>${translations[currentLanguage].finalScore}: ${score}</p>
    <p>${translations[currentLanguage].highScore}: ${highScore}</p>
    <p>${translations[currentLanguage].timeTaken}: ${seconds}${translations[currentLanguage].seconds}</p>
    <p>${translations[currentLanguage].pressEnter}</p>
  `;
  document.body.appendChild(gameOverScreen);

  document.addEventListener('keydown', handleGameOverKeydown);
}

function handleGameOverKeydown(event) {
  if (event.key === 'Enter') {
    document.removeEventListener('keydown', handleGameOverKeydown);
    const gameOverScreen = document.getElementById('game-over-screen');
    if (gameOverScreen) {
      gameOverScreen.remove();
    }
    initializeGame();
  }
}

function showComboMessage(comboCount) {
  const comboMessage = document.createElement('div');
  comboMessage.textContent = `${comboCount} ${translations[currentLanguage].combo}`;
  comboMessage.className = 'combo-message';
  document.body.appendChild(comboMessage);
  setTimeout(() => comboMessage.remove(), 1000);
}

// 使用 localStorage 保存最高分
function saveHighScore() {
  const highScore = localStorage.getItem('highScore') || 0;
  if (score > highScore) {
    localStorage.setItem('highScore', score);
  }
}

// 初始化游戏
document.addEventListener('DOMContentLoaded', () => {
  const difficultySelector = document.getElementById('difficulty-selector');
  Object.keys(DIFFICULTIES).forEach(difficulty => {
    const option = document.createElement('option');
    option.value = difficulty;
    option.textContent = translations[currentLanguage][difficulty];
    difficultySelector.appendChild(option);
  });
  difficultySelector.value = currentDifficulty;
  difficultySelector.addEventListener('change', (e) => setDifficulty(e.target.value));

  const newGameButton = document.getElementById('new-game');
  newGameButton.addEventListener('click', initializeGame);

  const hintButton = document.getElementById('hint');
  hintButton.addEventListener('click', showHint);

  const languageSelector = document.getElementById('language-selector');
  languageSelector.addEventListener('change', (e) => setLanguage(e.target.value));

  // 初始化翻译
  updateTranslations();

  // 初始调整大小并初始化游戏
  adjustGameSize();
  initializeGame();

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    adjustGameSize();
    updateBoard();
  });

  // 添加连击系统
  let combo = 0;
  let lastMatchTime = 0;

  function updateScore(points) {
    const now = Date.now();
    if (now - lastMatchTime < 1000) { // 1秒内的连续匹配
      combo++;
      points *= (1 + combo * 0.1); // 每次连击增加10%的分数
    } else {
      combo = 0;
    }
    lastMatchTime = now;
    
    score += Math.round(points);
    document.getElementById('score').textContent = `${translations[currentLanguage].score}: ${score}`;
    
    if (combo > 1) {
      showComboMessage(combo);
    }
  }
});